package BeenChina.PM.Util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import BeenChina.PM.Model.ModelUser;

public class CookieUtil {

	public static final String USER_COOKIE = "user.cookie.pmdata";  
	
	public static ModelUser getCookie(HttpServletRequest request)
	{
		ModelUser user= null;
		
		//HttpServletRequest request = ServletActionContext.getRequest();
		Cookie[] cookies = request.getCookies();
		
		if (cookies != null) {   
			for (Cookie c : cookies) {			   		   
				if (USER_COOKIE.equals(c.getName())) {				   
					JSONObject jsonObject = JSONObject.fromObject(c.getValue());		
					user = (ModelUser)JSONObject.toBean(jsonObject, ModelUser.class);					    
				}				   
			}			 
		}
		
		return user;
	}
	
	public static void setCookie(ModelUser user)
	{
		//encode pass
		String pasString = user.getUserPass();
		pasString = SecurityUtil.createPassword(pasString);
		user.setUserPass(pasString);
		
		HttpServletRequest request = ServletActionContext.getRequest();
		//String host = request.getServerName();		
		String contextPath=request.getContextPath();
				
		Cookie cookie = new Cookie(USER_COOKIE, JSONObject.fromObject(user).toString());
		//cookie.setDomain(host);
		cookie.setPath(contextPath);
		cookie.setMaxAge(60*60*24*7);
		
		HttpServletResponse response = ServletActionContext.getResponse();  
		response.addCookie(cookie);
	}

	public static void delCookie()
	{				  
		HttpServletRequest request = ServletActionContext.getRequest();		 
		Cookie[] cookies = request.getCookies();  		
		String contextPath=request.getContextPath();
		
		HttpServletResponse response = ServletActionContext.getResponse(); 		 
		for(int i=0;i<cookies.length;i++)
		{
		   	 if (USER_COOKIE.equals(cookies[i].getName())) { 
		   		 cookies[i].setMaxAge(0);		 
		   		 cookies[i].setPath(contextPath);
		         response.addCookie(cookies[i]);		      
		   	 }
		}		
	}
	
	public static boolean isSaveCookie()
	{				  
		HttpServletRequest request = ServletActionContext.getRequest();		 
		Cookie[] cookies = request.getCookies();   
		
		for(int i=0;i<cookies.length;i++)
		{
		   	 if (USER_COOKIE.equals(cookies[i].getName())) { 
		   		 return true;
		   	 }
		}
		return false;
	}
}
